<template>
<div class="main_spac1 maincl">
	<div class="main_white padding10">
		<div class="mainor_form">
		<div class="mainor_te">
			<el-button class="mainor_tea" @click="newDialog = true;">创建账单</el-button>
		</div>
		<el-form
				:inline="true"
				:model="form"
				class="demo-form-inline"
				ref="searchForm"
				label-width="80px"
			>
				<el-form-item label="账单">
					<el-input
						v-model.trim="form.order_sn"
						placeholder="账单号"
						clearable
					></el-input>
				</el-form-item>

				<el-form-item label="客户">
					<el-autocomplete
						v-model="form.company_name"
						:fetch-suggestions="queryCustoms"
						value-name=""
						placeholder="请输入客户"
						@select="selectCustom($event,'search')"
					>
						<template slot-scope="{ item }">
							<div>{{ item.company_name }}</div>
						</template>
					</el-autocomplete>
				</el-form-item>

				<el-form-item label="账期">
					<el-date-picker
						v-model="form.payment_days"
						type="month"
						value-format="yyyy-MM"
						placeholder="选择账期">
					</el-date-picker>
				</el-form-item>

				<el-form-item label="状态">
					<el-select v-model="form.pay_status"  placeholder="请选择" clearable>
						<el-option
						v-for="(val,index) in payStatusList"
						:key="index"
						:value="index"
						:label="val"
						>
						</el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="创建时间">
					<el-date-picker
					v-model="form.time"
					value-format="yyyy-MM-dd"
					type="daterange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
					>
					</el-date-picker>
				</el-form-item>
				<div class="clearfix"></div>
				<el-form-item class="marginTop10">
					<el-button
						class="reset marginLeft10"
						type="primary"
						@click="reset()"
						>重置</el-button
					>
					<el-button
						type="primary"
						@click="getArticleList"
						:loading="listLoading"
						>搜索</el-button
					>
				</el-form-item>
			</el-form>
		</div>

		<div class="main_table" style="min-height: 590px">
		<el-table
			ref="multipleTable"
			v-loading="listLoading"
			:data="list"
			element-loading-text="加载中"
			fit
			border
			highlight-current-row
		>
			<el-table-column type="selection" />

			<el-table-column
				label="客户"
				width="100"
				prop="company_name"
				:show-overflow-tooltip="true"
			>
			</el-table-column>

			<el-table-column
				label="账单号"
				width="200"
				prop="order_sn"
				:show-overflow-tooltip="true"
				
			>
				<template slot-scope="scope">
					<a @click="toDetail(scope.row.id)" style="color:#409EFF;">{{scope.row.order_sn}}</a>
				</template>
			</el-table-column>

			<el-table-column
				label="账期"
				prop="payment_days"
				:show-overflow-tooltip="true"
			/>

			<el-table-column
				label="配送金额"
				prop="send_money"
				:show-overflow-tooltip="true"
			/>
			<el-table-column
				label="佣金比例(‰)"
				prop="commission_rate"
				:show-overflow-tooltip="true"
				sortable
			/>

			<el-table-column
				label="佣金金额"
				width="100"
				prop="commission"
				:show-overflow-tooltip="true"
			>
			</el-table-column>

			<el-table-column
				label="抹零金额"
				prop="zero_money"
				:show-overflow-tooltip="true"
			/>
			<el-table-column
				label="实收金额"
				prop="real_money"
				:show-overflow-tooltip="true"
			/>

			<el-table-column
				label="状态"
				prop="pay_status"
				sortable
				:show-overflow-tooltip="true"
			>
				<template slot-scope="scope">
				<span :style="{color: scope.row.pay_status == 0 ? '#ff9900' : scope.row.pay_status == 1 ? '#19be6b':'#909399'}">
					{{ payStatusList[scope.row.pay_status]}}
				</span>
				</template>
			</el-table-column>

			<el-table-column
				label="支付剩余天数"
				prop="time_left"
				:show-overflow-tooltip="true"
			>
			</el-table-column>

			<el-table-column
				label="创建时间"
				prop="created_at"
				:show-overflow-tooltip="true"
				width="120"
			>
				<template slot-scope="scope">{{parseTime(scope.row.created_at, "{y}-{m}-{d}")}}</template>
			</el-table-column>

			<el-table-column fixed="right" label="操作" width="240" class-name="rightbtn">
				<template slot-scope="scope">
					<el-button
						@click="checkAction(scope.row)"
						type="text"
						size="mini"
						style="color:#19be6b"
						class="handle_btn"
						v-if="scope.row.pay_status==0 && scope.row.zero_status!=1"
					>对账</el-button>
					<el-button
						@click="zeroAction(scope.row)"
						type="text"
						size="mini"
						style="color:#ff9900"
						class="handle_btn"
						v-if="scope.row.pay_status==0"
					>抹零</el-button>
					<el-button
						@click="finalAction(scope.row)"
						type="text"
						size="mini"
						style="color:#19be6b"
						class="handle_btn"
						v-if="scope.row.pay_status==0"
					>结算</el-button>
					<el-button
						@click="cancelAction(scope.row.id,scope.row.company_name,scope.row.payment_days)"
						type="text"
						size="mini"
						style="color:#fa3534"
						class="handle_btn"
						v-if="scope.row.pay_status==0"
					>作废</el-button>
					<el-button
						@click="settingAction(scope.row.id)"
						type="text"
						size="mini"
						class="handle_btn"
						v-if="scope.row.pay_status==0"
					>设置</el-button>
				</template>
			</el-table-column>
		</el-table>
		</div>



		<div class="main_page boxdq">
		<div></div>
		<!-- 分页 -->
		<div class="main_page_r">
			<el-pagination
				:current-page="current.page"
				:page-sizes="[20, 30, 50, 100]"
				:page-size="limit"
				layout="total, sizes, prev, pager, next, jumper"
				:total="totalCount"
				background
				@size-change="changeLimit"
				@current-change="changePage"
			/>
		</div>
		</div>
	</div>  

	<!-- 结算弹窗 -->
	<el-dialog title="结算" class="finalDialog" :visible.sync="showFinalDialog" :close-on-click-modal="false">
		<div class="info">
			<div>
				<div class="row">
					<span class="label">客户：</span>
					<span class="value">{{finalInfo.company_name}}</span>
				</div>
				<div class="row">
					<span class="label">账单号：</span>
					<span class="value">{{finalInfo.order_sn}}</span>
				</div>
				<div class="row">
					<span class="label">账期：</span>
					<span class="value">{{finalInfo.payment_days}}</span>
				</div>
				<div class="row">
					<span class="label">配送金额：</span>
					<span class="value">{{finalInfo.send_money}}</span>
				</div>
			</div>
			<div>
				<div class="row">
					<span class="label">佣金比例：</span>
					<span class="value">{{finalInfo.commission_rate}}</span>
				</div>
				<div class="row">
					<span class="label">佣金金额：</span>
					<span class="value">{{finalInfo.commission}}</span>
				</div>
				<div class="row">
					<span class="label">抹零金额：</span>
					<span class="value">{{finalInfo.zero_money}}</span>
				</div>
				<div class="row">
					<span class="label">实收金额：</span>
					<span class="value">{{finalInfo.real_money}}</span>
				</div>
			</div>
		</div>
		<el-form :model="finalForm" label-width="100px">
			<el-form-item label="收款渠道">
				<el-select v-model="finalForm.collection_channels" placeholder="请选择收款渠道" style="width:180px;">
					<el-option label="银行转账" value="2"></el-option>
					<el-option label="支付宝" value="3"></el-option>
					<el-option label="微信" value="4"></el-option>
					<el-option label="现金" value="5"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="付款人" >
				<el-input v-model="finalForm.payer" placeholder="请输入付款人"></el-input>
			</el-form-item>
			<el-form-item label="备注">
				<el-input type="textarea" v-model="finalForm.remark" placeholder="请输入备注"></el-input>
			</el-form-item>
			<el-form-item label="上传凭证" prop="img" style="margin-bottom: 30px">
              <el-upload
                class="avatar-uploader"
                :action="uploadPath"
                :data="{ store: 'document' }"
                :on-success="handSuccess"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :limit="3"
                list-type="picture-card"
              >
                <div class="slot" slot="default">
                  <i class="el-icon-plus"></i>
                </div>
              </el-upload>
            </el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer" style="margin-top:20px;">
			<el-button @click="showFinalDialog = false">取 消</el-button>
			<el-button type="primary" @click="submit('final')">确 定</el-button>
		</div>
	</el-dialog>

	<!-- 对账弹窗 -->
	<el-dialog title="对账" :visible.sync="showCheckDialog" :close-on-click-modal="false">
		<el-form :model="checkForm">
			<el-form-item label="配送金额" >
				<el-input v-model="checkForm.send_money"></el-input>
			</el-form-item>
			<el-form-item label="佣金比例" >
				<el-input-number v-model="checkForm.commission_rate" :step="1" :min="0" controls-position="right" step-strictly></el-input-number> ‰
				<!-- <el-input v-model="checkForm.commission_rate">
				<template slot="append">‰</template>
				</el-input> -->
			</el-form-item>
			<el-form-item label="佣金金额" >
				<el-input v-model="totalCommission" disabled></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="showCheckDialog = false">取 消</el-button>
			<el-button type="primary" @click="submit('check')">确 定</el-button>
		</div>
	</el-dialog>

	<!-- 抹零弹窗 -->
	<el-dialog title="抹零" class="zero_dialog" :visible.sync="showZeroDialog" :close-on-click-modal="false">
		<el-alert
			title="注意"
			type="warning"
			description="保存抹零后，不可再进行对账！"
			:closable="false"
			show-icon>
		</el-alert>
		<el-form :model="zeroForm">
			<el-form-item label="佣金金额" >
				<el-input v-model="zeroForm.commission" disabled></el-input>
			</el-form-item>
			<el-form-item label="抹零金额" >
				<el-input-number v-model="zeroForm.zero_money" :step="0.1" @change="totalZeroMoney" controls-position="right" :min="0" :max="Number(zeroForm.commission)"></el-input-number>
				<!-- <el-input v-model="zeroForm.zero_money" type="number"></el-input> -->
			</el-form-item>
			<el-form-item label="实收金额" >
				<el-input v-model="zeroForm.real_money" disabled></el-input>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="showZeroDialog = false">取 消</el-button>
			<el-button type="primary" @click="submit('zero')">确 定</el-button>
		</div>
	</el-dialog>

	<!-- 设置弹窗 -->
	<el-dialog title="设置" :visible.sync="showSettingDialog" :close-on-click-modal="false">
		<el-form :model="settingForm">
			<el-form-item >
				第 <el-input-number v-model="settingForm.notice_days"  :max="settingForm.forbid_days" controls-position="right" step-strictly></el-input-number> 天开始提醒
			</el-form-item>
			<el-form-item >
				第 <el-input-number v-model="settingForm.forbid_days" :min="settingForm.notice_days" controls-position="right" step-strictly></el-input-number> 天关闭系统
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="showSettingDialog = false">取 消</el-button>
			<el-button type="primary" @click="submit('setting')">确 定</el-button>
		</div>
	</el-dialog>

	<!-- 创建账单弹窗 -->
	<el-dialog title="创建账单" :visible.sync="newDialog" :close-on-click-modal="false">
		<el-form :model="newForm" :rules="rules" ref="newForm">
			<el-form-item label="客户" prop="company_name">
				<el-autocomplete
					v-model="newForm.company_name"
					:fetch-suggestions="queryCustoms"
					clearable
					placeholder="请输入客户"
					@select="selectCustom($event)"
				>
					<template slot-scope="{ item }">
						<div>{{ item.company_name }}</div>
					</template>
				</el-autocomplete>
			</el-form-item>

			<el-form-item label="账期" prop="payment_days">
				<el-date-picker
					v-model="newForm.payment_days"
					type="month"
					value-format="yyyy-MM"
					:picker-options="pickerOptions"
					placeholder="请选择账期">
				</el-date-picker>
			</el-form-item>

		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button @click="newDialog = false;resetForm('newForm')">取 消</el-button>
			<el-button type="primary" @click="submit('new')">确 定</el-button>
		</div>
	</el-dialog>
	<el-dialog :visible.sync="dialogVisible">
		<img :src="dialogImageUrl" alt />
	</el-dialog>
</div>
</template>

<script>
import { offlineCommissionList,invalidBill,account,zero,getBillDays,setBill,getCompanyListByName,addBill,settlement } from "@/api/brokerage/offline";
import { parseTime } from "@/utils/index";
import { uploadPath, puzzleImg } from "@/api/currency";
export default {
data() {
	return {
		dialogImageUrl: "",
      dialogVisible: false,
		uploadPath,
      puzzleImg,
		// 时间
		parseTime,
		// 分页
		current: {
		page: 1,
		size: 20,
		},
		limit: 20,
		totalCount: 1,
		// 搜索
		form: {},
		//   model: [],
		start_time: "",
		end_time: "",
		// 列表数据
		list: [],
		listLoading: false,
		// 全选
		selectArr: [],
		payStatusList: [], //状态列表
		showCheckDialog:false,  //控制对账弹窗
		checkForm:{}, //对账弹窗数据
		showZeroDialog:false,  //控制抹零弹窗
		zeroForm:{}, //抹零弹窗数据
		showSettingDialog:false,  //控制设置弹窗
		settingForm:{}, //设置弹窗数据
		newDialog:false,  //新建账单弹窗
		newForm:{},		//新建账单数据
		showFinalDialog:false,	//控制结算弹窗
		finalForm:{},
		finalInfo:{},	//结算显示的信息
		pics:[],	//结算上传的图片

		rules:{
			company_name:[
				{required:true,message:'请输入客户',trigger:['change','blur']}
			],
			payment_days:[
				{required:true,message:'请选择账期',trigger:'blur'}
			]
		},
		pickerOptions:{
			disabledDate(time) {
				let bool = false;
				if(time.getFullYear() > new Date().getFullYear()){
					bool =  true;
				}
				else if(time.getFullYear() == new Date().getFullYear() && time.getMonth() > new Date().getMonth()-1){
					bool =  true
				}
				return bool;
          },
		},
	};
},
mounted() {
	this.getData();
},
computed:{
	totalCommission:function(){
		let total = Number(this.checkForm.send_money) * Number(this.checkForm.commission_rate)/1000
		total = total.toFixed(2)
		this.checkForm.commission = total;
		return total;
	},
},
methods: {
	//结算
	finalAction(row){
		this.finalInfo = row;
		this.finalForm.id = row.id;
		this.showFinalDialog = true;
	},
	//作废
	cancelAction(id,name,days) {
		this.$confirm(`确认作废客户【${name}】账期为【${days}】的账单`, '作废', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			let data = {id}
			invalidBill(data).then((res) => {
				if (res.errcode == 0) {
					this.$message.success( '作废成功!');
					this.getData();
				} else {
					this.$message.error(res.errmsg);
				}
			});
			
		})
	},
	//对账
	checkAction(row) {
		let {id,send_money,commission_rate,commission} = row;
		commission_rate = commission_rate.replace('‰','');
		this.checkForm = {
			id,send_money,commission_rate,commission
		}
		this.showCheckDialog = true;
	},
	//抹零
	zeroAction(row) {
		let {id,commission} = row;
		this.zeroForm = {
			id,commission,
			real_money:commission,
			zero_money:0
		}
		this.showZeroDialog = true;
	},
	//设置
	settingAction(id) {
		getBillDays({id}).then((res) => {
			if (res.errcode == 0) {
				this.settingForm = {
					id,
					notice_days:res.data.notice_days,
					forbid_days:res.data.forbid_days,
				}
				this.showSettingDialog = true;
			} else {
				this.$message.error(res.errmsg);
			}
		});
	},
	//抹零计算实收金额
	totalZeroMoney(e){
		this.zeroForm.zero_money = e;
		let total = (Number(this.zeroForm.commission) - e).toFixed(2);
		this.zeroForm.real_money = total;
		return total;
	},
	selectCustom(e,type){
		if(type == 'search'){
			this.form.company_id = e.id;
			this.form.company_name = e.company_name;
		}else{
			this.newForm.company_id = e.id;
			this.newForm.company_name = e.company_name;
		}
	},
	//去账单详情
	toDetail(id){
		this.$router.push({
			path:`/brokerage/offline/offline_order_detail?id=${id}`,
		})
	},
	//搜索客户列表
	queryCustoms(str,callback){
		let params = {company_name:str,model:2};
		getCompanyListByName(params).then((res) => {
			if (res.errcode == 0) {
				callback(res.data.list)
			} else {
				this.$message.error(res.errmsg);
			}
		});
	},
	// 搜索
	getArticleList() {
		this.current.page = 1;

		this.getData();
	},
	// 分页
	changeLimit(pageSize) {
		this.current.per_page = pageSize;
		this.getData();
	},
	changePage(page) {
		this.current.page = page;
		this.getData();
	},
	// 获取列表
	getData() {
		this.listLoading = true;
		var search = this.list_form();
		let data = Object.assign(search, this.current)
		offlineCommissionList(data).then((res) => {
			this.listLoading = false;
			if (res.errcode == 0) {
				this.list = res.data.list;
				this.payStatusList = res.data.pay_status_List
				this.totalCount = res.data.count;
			} else {
				this.$message.error(res.errmsg);
			}
		});
	},
	//处理搜索表单
	list_form() {
		let form = {};
		for (let i in this.form) {
			if (this.form[i] != "") {
				form[i] = this.form[i];
			}
		}
		if(form.company_name){
			delete form.company_name;
		}
		if(form.time){
			form.created_time_start = form.time[0];
			form.created_time_end = form.time[1];
			delete form.time;
		}
		return form;
	},
	reset() {
		this.form = {};
		this.getData();
	},
	resetForm(formName) {
		this.$refs[formName].resetFields();
	},
	  // 上传图片-删除
	handleRemove(file) {
	  const i = this.pics.findIndex(
		(item) => item.path == file.path
	  );
	  this.pics.splice(i, 1);
	},
	// 上传图片-查看
	handlePictureCardPreview(file) {
	  this.dialogImageUrl = file.url;
	  this.dialogVisible = true;
	},
	// 上传图片-成功
	handSuccess(res, file, fileList) {
		this.pics.push(res.data.path);
		//文件过大上传失败是接口拒绝，但是组件还是默认上传成功了，所以要先加上数据上传失败再删掉
		if(res.errcode != 0){
			this.$message.error(res.errmsg);
			this.handleRemove(file)
		}
	},
	submit(type){
		if(type == 'check'){
			let params = this.checkForm;
			account(params).then((res) => {
				if (res.errcode == 0) {
					this.$message.success('对账成功');
					this.showCheckDialog = false;
					this.getData()
				} else {
					this.$message.error(res.errmsg);
				}
			});
		}else if(type == 'zero'){
			this.$confirm('保存抹零后，不可再进行对账，确认保存吗', '保存', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(()=>{
				let params = this.zeroForm;
				delete params.commission;
				zero(params).then((res) => {
					if (res.errcode == 0) {
						this.$message.success('抹零成功');
						this.showZeroDialog = false;
						this.getData()
					} else {
						this.$message.error(res.errmsg);
					}
				});
			})
		}else if(type == 'setting'){
			let params = this.settingForm;
			setBill(params).then((res) => {
				if (res.errcode == 0) {
					this.$message.success('设置成功');
					this.showSettingDialog = false;
					this.getData();
				} else {
					this.$message.error(res.errmsg);
				}
			});
		}else if(type == 'new'){
			this.$refs.newForm.validate((valid)=>{
				if(valid){
					let params = this.newForm;
					delete params.company_name;
					addBill(params).then((res) => {
						if (res.errcode == 0) {
							this.resetForm('newForm');
							this.$message.success('提交成功');
							this.newDialog = false;
							this.getData()
						} else {
							this.$message.error(res.errmsg);
						}
					});
				}
			})
		}else if(type == 'final'){
			let params = this.finalForm;
			let credentials = '';
			if(this.pics.length>0){
				credentials = this.pics.join(',');
			}
			Object.assign(params,{credentials});
			settlement(params).then((res) => {
				if (res.errcode == 0) {
					this.$message.success('结算成功');
					this.showFinalDialog = false;
					this.getData()
				} else {
					this.$message.error(res.errmsg);
				}
			});
		}
	},
},
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.maincl {
.el-select {
	width: 114px;
}
.more {
	margin-left: 50px;
}
.handle_btn {
	padding: 0;
	border: 0;
}
.edit_dialog {
	.address {
		max-width: 350px;
	}
}

.mainor_form form {
	// width: calc(100% - 180px);
	width: 100%;
}

.main_table /deep/.el-table--small td {
	padding: 10px 0;
}
.main_table /deep/.el-table--small th {
	padding: 10px 0;
}
.zero_dialog{
	/deep/.el-dialog__body{
		padding-top:0;
	}
	/deep/.el-alert{
		margin-bottom:20px;
	}
}

/deep/.el-table {
	tr {
		&:hover {
		background: none !important;
		}
		&.hover-row > td {
		background: none !important;
		}
		.current-row > td {
		background: none !important;
		}
	}
}
/deep/.el-table .el-table__body tr:hover {
	background: #fff !important;
}
/deep/.el-table .el-table__body tr:hover > td {
	background: #fff !important;
}
/deep/.el-table tr.expanded + tr {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr > td {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr .mainex_ta {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr .mainex_ta th,
/deep/.el-table tr.expanded + tr .mainex_ta tr {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr:hover {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr:hover > td {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr .el-table tr:hover {
	background: #fafafa !important;
}
/deep/.el-table tr.expanded + tr .el-table tr:hover > td {
	background: #fafafa !important;
}
}
.finalDialog{
	.info{
		margin-bottom:20px;
		overflow: hidden;
		>div{
			width:50%;
			float: left;
			.row{
				margin-bottom:10px;
				.label{
					color:#999;
					width:100px;
					text-align: right;
					display: inline-block;
				}
			}
		}
	}
}
.el-table{
	.cell{
		display: flex;
		flex-wrap: wrap;
	}
}
</style>
